﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace OAuth2Authorizer.Serialization
{
    internal class NameValueCollectionSerializer : ISerializer<NameValueCollection>
    {
        private static readonly int bufferSize = 4096;
        public NameValueCollection ReadObject(Stream stream)
        {
            var memoryStream = new MemoryStream();
            byte[] buffer = new byte[bufferSize];
            int bytesRead = 0;
            while((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                memoryStream.Write(buffer, 0, bytesRead);
            }
            byte[] objectArray = memoryStream.ToArray();
            string objectString = Encoding.UTF8.GetString(objectArray);
            return GetCollection(objectString);
        }

        public void WriteObject(Stream stream, NameValueCollection obj)
        {
            string objString = GetFormEncodedString(obj);
            byte[] buffer = Encoding.UTF8.GetBytes(objString);
            stream.Write(buffer, 0, buffer.Length);
        }

        internal NameValueCollection GetCollection(string formEncodedString)
        {
            var collection = new NameValueCollection();
            var properties = formEncodedString.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var property in properties)
            {
                var tokens = property.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                collection.Add(tokens[0], tokens[1]);
            }
            return collection;
        }

        internal string GetFormEncodedString(NameValueCollection parameters)
        {
            var parameterString = string.Empty;
            if (parameters != null && parameters.Count > 0)
            {
                foreach (var key in parameters.AllKeys)
                {
                    parameterString += string.Format("{0}={1}&", key, parameters[key]);
                }
                parameterString = parameterString.Substring(0, parameterString.Length - 1);
            }
            return parameterString;
        }
    }
}
